﻿using Cysharp.Threading.Tasks;
using IQIGame.Onigao.Framework;
using IQIGame.Onigao.Game;
using IQIGame.USDK;


namespace IQIGame.Onigao.GamePlay
{
    /// <summary>
    /// 类名 : 登录模块
    /// 作者 : Canyon / 龚阳辉
    /// 日期 : 2024-05-11 14:38
    /// 功能 : 包括登录和选角 (GameServerModule,LoadPlayerModule,ManagerCenter)
    /// </summary>
    public class LoginModule : Singleton<LoginModule>
    {
        private LoginModule()
        {
        }

        /// <summary>
        /// 是否登录中
        /// </summary>
        private bool logging = false;

        /// <summary>
        /// 登录-游戏
        /// </summary>
        public async UniTaskVoid LoginGameAsync(LoginResponseServerInfo selectServer, LoginResponseUserLogin userLoginResponse)
        {
            if (logging)
            {
                return;
            }
            logging = true;
            try
            {
                // 连接游戏服
                NetSession session = await NetManager.Instance.ConnectToChannel(NetworkChannelName.Game, CGameNetHandler.Instance, GameServerModule.Instance, selectServer.serverIp, selectServer.port);

                // 连接结果
                if (session == null)
                {
                    NoticeModule.ShowNoticeNoCall(NoticeConstant.ID_NET_ERROR_ON_CONNECT_GAME_SERVER);
                    return;
                }
                bool connectServer = await session.SessionConnector.ConnectServer(session, userLoginResponse.data.token, selectServer.serverId, userLoginResponse.data.accountServerId);
                if (!connectServer)
                {
                    //协议连接失败
                    return;
                }
            }
            finally
            {
                logging = false;
            }

            GameDataCenter.CurrGameServerInfo = selectServer;
            if (ManagerCenter.ProjectSetting.IsSDKMode())
            {
                IQIUSDK.Instance.roleSelectServer(SDKModule.Instance.CreateDefaultRole());
            }
            LoadPlayerModule.Instance.RequestRoleList().Forget();
        }

        /// <summary>
        /// 登录-用户
        /// </summary>
        public UniTask<LoginResponseUserLogin> LoginUserAsync(LoginRequestBaseData loginRequestBaseData)
        {
            return new LoginWebRequest<LoginResponseUserLogin>().SendRequest(LoginMethod.UserLogin, loginRequestBaseData);
        }

    }
}
